<?php
namespace app\admin\controller;

use app\admin\library\AdminController;
use cubox\Cubox;


use app\admin\library\User  as adminUser;

class  User extends AdminController{
    
    private string $manageAdminUserGroup = '';
    
    public function __construct()
    {
        parent::__construct();

        if (adminUser::super()){
            $this->manageAdminUserGroup = 'all';
        }else{
            $this->manageAdminUserGroup =  adminUser::getPowerExtend('admin','admin.user','manageAdminUserGroup','self');
        }
    
    }
    public function onIndex(){
        $this->power('admin.user');
        $this->pageTitle = '管理员';
        $this->pageIcon = 'fa-user';
        return $this->display();
    }
    
    public function onLogout(){
        adminUser::logout();
        Cubox::go($this->app->url('outside','login'));
    }

    public function onList(){

        $this->power('admin.user');

        $group_id = $this->post('group_id',$this->check('分组')->type('int'));
        $status   = $this->post('status',$this->check('状态')->type('string'));
        $keyword   = $this->post('keyword',$this->check('查询')->type('string'));

        $pageCurrent = $this->post('page_current',$this->check('当前页')->default(1)->type('int'));

        $user = $this->model('User');
        
        if ($group_id){

            $group = $this->model('UserGroup');
            
            $user->where('group_id','in',$group->getKeyCollect($group_id));
        }

        if ($this->manageAdminUserGroup!='all'){
            $user->where('group_id','in',$this->getPowerGroupList('manage',$this->manageAdminUserGroup));
        }


        if ($status){
            $user->where('status',$status);
        }

        if ($keyword){
            $user->where(['username','nickname'],'like','%'.trim($keyword).'%');
        }
        

        $list = $user->page($pageCurrent,20)->order('create_time','DESC')->getData();

        foreach ($list as $key => $value) {
            $list[$key] = $this->formate($value);
        }
         
        return ['list' => $list,'total'=>$user->total,'count'=>$user->pageCount];
    }


    public function onEdit(){
        $user_id  = $this->get('id',$this->check('ID')->type('int'));
        $this->pageTitle = '添加管理员';
        $this->pageIcon = 'fa-user';
        $user = $this->model('User');
        if ($user_id){
            $data  = $user->getId($user_id);

            if (!$this->inGroupPower($data['group_id'])){
                throw new \Exception('没有权限');
            }

            if ($data){

                if ($data['power_extend']){
                    try{
                        $data['power_extend'] = json_decode($data['power_extend'],true);
                    }catch(\Exception $e){
                        $data['power_extend'] = [];
                    }
                    
                }else{
                    $data['power_extend'] = [];
                }

                $this->set('user',$data);
                $this->pageTitle = '编辑管理员';
            }else{
                throw new \Exception('管理员不存在');
            }
        }

        return $this->display();
    }

    public function  onSave(){
        $this->power('admin.user.edit');

        $data['username'] =  $this->post('username',$this->check('用户名')->required()->maxLength(16));
        $data['nickname'] =  $this->post('nickname',$this->check('昵称')->required()->maxLength(20));
        $data['photo'] =  $this->post('photo');
        $data['group_id'] = $this->post('group_id',$this->check('管理员分组')->type('int')->required());
        $data['power'] =  $this->post('power',$this->check('权限')->type('string'));
        
        $power_extend =$this->post('power_extend',array());
        $data['power_extend'] =  json_encode($power_extend );
        
        $update_at =  $this->post('update_at');

        $user_id = $this->post('user_id',$this->check('User ID')->type('int'));

        if (!$this->inGroupPower($data['group_id'])){
            throw new \Exception('没有权限');
        }

        //验证权限
        if (count($power_extend)>0 && !$this->checkPowerExtend($power_extend)){
            throw new \Exception('权限不足');
        }


        $user = $this->model('User');

        if ($user_id){

            //获取旧数据
            $oldData = $user->getId($user_id);

            if (!$oldData){
                throw new \Exception('管理员不存在');
            }

            if ($oldData['update_at'] != $update_at ){
                throw new \Exception('数据已修改,请刷新页面');
            }

            if ($user->updateId($user_id,$data)){

                $this->log('编辑管理员',$data);

                return true;
            }else{
                throw new \Exception('保存失败');
            }
        }else{

            if ($user->where('username',$data['username'])->count()>0){
                throw new \Exception('用户名已存在');
            }

            //判断用户组权限

            $data['status'] = 'new';
            $password = $this->post('password',$this->check('密码')->required());
            $data['password'] = adminUser::makePassword($password);
            $data['create_time'] = time();
            
            if ($user->insert($data)){
                $this->log('添加管理员',$data);
                return true;
            }else{
                throw new \Exception('保存失败');
            }
        }
        
    }

    public function onStatus(){
        $this->power('admin.user');

        $users = $this->post('users',$this->check()->type('array')->required());
        $status =$this->post('status',$this->check()->type('string')->required());
        $user = $this->model('User');


        $userData = $user->where('user_id','in',$users)->getData();

        foreach($userData as $v){
            if ($v['user_id'] == adminUser::get('user_id')){
                throw new \Exception('不能修改自己的状态');
            }

            if ($v['power']=='ALL') {
                throw new \Exception('不能修改超级管理员状态');
            }

            if (!$this->inGroupPower($v['group_id'])){
                throw new \Exception('超过修改权限');
            }

        }
        
        if ($user->where('user_id','in',$users)->update(['status'=>$status])){
            $this->log('修改管理员状态',['status'=>$status,'users'=>$users]);
            return true;
        }else{
            throw new \Exception('修改失败');
        }

    }


    public function onResetPassword(){
        $this->power('admin.user.resetPassword');

        $user_id = $this->post('user_id',$this->check('User ID')->required()->type('int'));
        $password = $this->post('password',$this->check('密码')->required());

        $user = $this->model('User');

        if(!$user_id){
            throw new \Exception('参数错误');
        }


        $oldData =  $user->getId($user_id);
        
        if (!$this->inGroupPower($oldData['group_id'])){
            throw new \Exception('没有权限');
        }

        $data ['password'] = adminUser::makePassword($password);
        $data ['status'] = 'new';


        if ($user->updateId($user_id, $data )){
            $this->log('重置密码',['user_id'=>$user_id]);
            return true;
        }else{
            throw new \Exception('重置失败');
        }
        
    }


    public function onDel(){
        $this->power('admin.user.del');
        $user_id = $this->post('user_id',$this->check('User ID')->required()->type('int'));
        
        $user = $this->model('User');
        
        $data = $user->getId($user_id);
        
        if (!$this->inGroupPower($data['group_id'])){
            throw new \Exception('没有权限');
        }

        if ($user->deleteId($user_id)){
            $this->log('删除管理员',$data);
            return true;
        }else{
            throw new \Exception('删除失败');
        }
        
    }

    public function onGroup(){
        $this->power('admin.user.group');
        $this->pageTitle = '管理员组';
        return $this->display();
    }

    public function onGroupList(){
        $this->power('admin.user.group');
        $group = $this->model('UserGroup');

        $list = $group->getTreeData(0);
        if($this->manageAdminUserGroup != 'all'){
            $powerList = $this->getPowerGroupList('manage',$this->manageAdminUserGroup);
            
            $list = $this->delUnPowerNode($list,$powerList);
        }

        return ['list' => $list];
    }


    private function delUnPowerNode($list,$powerList){
        $re = [];
        foreach ($list as $key => $value) {
            if (in_array($value['group_id'],$powerList)){
                
                if ($value['children'] && count($value['children'])>0){
                    $value['children'] =  $this->delUnPowerNode($value['children'],$powerList);
                }

                $re[]= $value;
            }
        }

        return $re;
    }

    public function onGroupEdit(){
        $group_id = $this->get('id',$this->check('Group ID')->type('int'));

        $groupData  = [];
        $this->pageTitle = '添加管理员组';
        if ($group_id){
            if (!$this->inGroupPower($group_id)){
                throw new \Exception('没有权限');
            }

            $group = $this->model('UserGroup');
            $groupData = $group->getId($group_id);

            if ($groupData['power_extend']){
                try{
                    $groupData['power_extend'] = json_decode($groupData['power_extend'],true);
                }catch(\Exception $e){
                    $groupData['power_extend'] = [];
                }
                
            }else{
                $groupData['power_extend'] = [];
            }
            
            $this->pageTitle = '编辑管理员组';

            if (!$groupData){
                throw new \Exception('Group not found.');
            }
        }

        $this->set('group',$groupData);
        return $this->display('user_group_edit');
    }

    public function onLog(){
        $this->power('admin.user.log');
        
        $user_id = $this->get('id',$this->check('ID')->type('int'));


        if ($user_id){
            $user = $this->model('User');
            $data = $user->getId($user_id);
            if (!$this->inGroupPower($data['group_id'])){
                throw new \Exception('没有权限');
            }
            $this->pageTitle =$data['nickname'].'的用户日志';
        }else{
            $user_id = adminUser::get('user_id');
            $this->pageTitle ='我的日志';
            $this->pageIcon = 'fa-calendar';
            $this->set('my',true);
        }
            //获取用户信息
       
        $userLog  = $this->model('UserLog');

        $appList =  $userLog->where('user_id',$user_id)->group('app')->getData('app');
        $appInfoList =  Cubox::getAppList();
        $appOption = [];
        foreach($appList as $val){
            $name = $val['app'];
            if (isset($appInfoList[$name])){
                $appOption[] = ['value'=>$name,'label'=>$appInfoList[$name]['title']?:''];
            }else{
                $appOption[] = ['value'=>$name,'label' => $name];
            }
        }

        
        $this->set('user_id',$user_id);
        $this->set('appOption',$appOption);
        return $this->display();
    }
    
    public function onLogList(){
        
        $user_id =  $this->post('user_id',$this->check('ID')->type('int')->required());
        $app = $this->post('app');
        $time = $this->post('time');
        $keyword  = $this->post('keyword');

        if (adminUser::get('user_id') != $user_id){
             
            $this->power('admin.user.log');
        }

        $pageCurrent = $this->post('page_current',1);
        
        $user = $this->model('User');
        $data = $user->getId($user_id);
        if (!$this->inGroupPower($data['group_id'])){
            throw new \Exception('没有权限');
        }

        $userLog  = $this->model('UserLog');
        $userLog->where('user_id',$user_id);
        
        
        if ($app){
            $userLog->where('app',$app);
        }

        if ($time){
            switch($time){
                case "today":
                //查询今天的数据
                    $userLog->where('time','>=',time()-86400);
                    break;
                case "yesterday":
                    //查询昨天的数据
                    $userLog->where('time','>=',time()-86400*2);
                    break;
                case "week":
                    //查询本周的数据
                    $userLog->where('time','>=',time()-86400*7);
                    break;
                case "month":
                    //查询本月的数据
                    $userLog->where('time','>=',time()-86400*30);
                break;
            }
        }


        if ($keyword){
            $userLog->where(['title','ip','content'],'LIKE','%'.trim($keyword).'%');
        }

        $list = $userLog->page($pageCurrent,20)->order('time','DESC')->getData();

        foreach($list as $key => $value){
            
            $value['datetime'] =  date('Y-m-d H:i:s',$value['time']);

            $content = '';
            if ($value['content']!=''){
                try{
                    $content = var_export(unserialize($value['content']),true);
                }catch(\Exception $e){
                    $content = 'error';
                }
                
            }

            $value['content'] = trim($content) ;
            //unset($value['content']);
            
            $list[$key] =$value;
        }
         
        return ['list' => $list,'total'=>$userLog->total,'count'=>$userLog->pageCount];
    }

    public function onGroupSave(){
        $this->power('admin.user.group');

        $data['title'] =  $this->post('title',$this->check('分组标题')->required()->maxLength(20));
        $data['parent_id'] = $this->post('parent_id',$this->check('上一级分组')->type('int')->required());
        $data['power'] =  $this->post('power',$this->check('权限')->type('string'));
        //
        $power_extend =  $this->post('power_extend',array());

        $group_id =  $this->post('group_id',$this->check('ID')->type('int'));

        $powerList = explode(',',$data['power']?:'');

        $update_at =  $this->post('update_at');

        foreach($powerList as $key => $value){
            if (!$this->power($value,true)){
                throw new \Exception('权限错误');
            }
        }

        if (!$this->inGroupPower($data['parent_id'])){
            throw new \Exception('没有权限');
        }

        if (count($power_extend)>0 && !$this->checkPowerExtend($power_extend)){
            throw new \Exception('权限不足');
        }

        $data['power_extend'] =  json_encode($power_extend);
        $group = $this->model('UserGroup');

        if ($group_id){
            if (!$this->inGroupPower($group_id)){
                throw new \Exception('没有权限');
            }

            //获取旧数据
            $oldData = $group->getId($group_id);
            if (!$oldData){
                throw new \Exception('数据不存在');
            }

            if ($oldData['update_at'] != $update_at){
                throw new \Exception('数据已被修改');
            }
            
            if ($group->updateId($group_id,$data)){
                $this->log('修改分组',$data);
                $this->clearPowerExtendCache();
                return true;
            }else{
                throw new \Exception('保存失败');
            }
        }else{
            if ($group->insert($data)){
                $this->clearPowerExtendCache();
                $this->log('添加分组',$data);
                return true;
            }else{
                throw new \Exception('保存失败');
            }
        }
    }

    public function onGroupDel(){
        $this->power('admin.user.group');

        $group_id =  $this->post('group_id',$this->check('ID')->required()->type('int'));


        if (!$this->inGroupPower( $group_id )){
            throw new \Exception('没有权限');
        }


        $group = $this->model('UserGroup');


        $groupData = $group->getId($group_id);

        if (!$groupData){
            throw new \Exception('分组不存在');
        }


        if ($group->where('parent_id',$group_id)->count()>0){
            throw new \Exception('请先删除子分组');
        }

        $user = $this->model('User');
        
        if ($user->where('group_id',$group_id)->count()>0){
            throw new \Exception('请先删除该分组下的管理员');
        }

        if ($group->deleteId($group_id)){
            
            $this->clearPowerExtendCache();

            $this->log('删除分组',$groupData);
            return true;
        }else{
            throw new \Exception('删除失败');
        }

    }

    public function onGroupOption(){
        $group = $this->model('UserGroup');
        $list = $group->getTreeData(0);
        if($this->manageAdminUserGroup != 'all'){
            $powerList = $this->getPowerGroupList('manage',$this->manageAdminUserGroup);
            $list = $this->delUnPowerNode($list,$powerList);
        }      
        return $list;
    }


    public function onSearchGroupOption(){
        $searchUserGroup =  adminUser::getPowerExtend('admin','*','searchAdminUser','self');
        if (adminUser::super()){
            $searchUserGroup = 'all';
        }

        $group = $this->model('UserGroup');
        $list = $group->getTreeData(0);
        if($searchUserGroup != 'all'){
            $powerList = $this->getPowerGroupList('search',$searchUserGroup);
            $list = $this->delUnPowerNode($list,$powerList);
        }

        return $list;

    }


    public function onPowerTree(){
        $plugs =  Cubox::plug('AdminPower');
        
        $group_id= $this->post('group',$this->check()->type('int')->default(0));

        $group = $this->model('UserGroup');
        
        $groupPower = '';
        $groupPowerExtend = [];
        if ($group_id!=0){
            $groupPowerArr =  $group->power($group_id);
            $groupPower =  $groupPowerArr['power'];
            $groupPowerExtend  =  $groupPowerArr['extend'];
        }

        $list  = [];

        foreach($plugs as $plug){
            $list[] = $plug->getData('',adminUser::get('power'),$groupPower);
        }

        $allPowerTitle =  $this->expandPowerTree($list);


        $re = ['tree'=>$list,'groupPower'=>$groupPower,'groupPowerExtend'=>$groupPowerExtend,'allPowerTitle'=>$allPowerTitle];
        
        $re['userPowerExtend'] =  adminUser::get('power_extend');
        
        return $re;
    }

 

    private function expandPowerTree($tree){
        $list = [];
        foreach($tree as $k => $v){

            if (!$v) continue;
            $list[$v['power']] = $v['title'];
            if(isset($v['children'])){
                $list = array_merge($list,$this->expandPowerTree($v['children']));
            }
        }
        return $list;
    }

    private function formate($data){
        unset($data['password']);
        return $data;
    }



    private function inGroupPower($id){
        
        if ($this->manageAdminUserGroup=='all') return true;

        $list = $this->getPowerGroupList('manage',$this->manageAdminUserGroup);

        if (in_array($id,$list)){
            return true;
        }else{
            return false;
        }
    }

    private function getPowerGroupList($type,$userGroupPower){

        $data = adminUser::get('admin-'.$type.'-grouplist');
        if ($data){
            return $data;
        }else{
             
            if ($userGroupPower=='self'){
                $groupList [] = ['group_id'=>adminUser::get('group_id')];
            }
            
            if ($userGroupPower=='custom'){

                if ($type=='manage')  $groupList = adminUser::getPowerExtend('admin','admin.user','manageGroupList',[]);
                if ($type=='search')  $groupList = adminUser::getPowerExtend('admin','*','searchUserGroupList',[]);
            }
            
            $list = [];
            if (count($groupList)>0){

                $group = $this->model('UserGroup');

                foreach($groupList as $groupItem){
                    if (!in_array($groupItem['group_id'],$list)){
                        $list = array_merge($list,$group->getKeyCollect($groupItem['group_id']));
                    }    
                }
            }

            adminUser::set('admin-'.$type.'-grouplist',$list);
            return $list;
        }
    }

    /**
     * 权限判断
     * @param string $power
     * @return boolean
     */

    private function checkPowerExtend($data){
        $plugs =  Cubox::plug('AdminPowerExtendCheck');

        if (is_array($data) && count($data)>0){
            foreach($data as $power =>$powerList){
                foreach($powerList as $app => $appData){
                    foreach($appData as $name => $data){
                        if (isset($plugs[$app])){
                            if (method_exists($plugs[$app],$name)){
                                if (!$plugs[$app]->$name($power,$data)){
                                    if (CUBOX_DEBUG){
                                        throw new \Exception('权限验证失败,当前管理员不能设置这个权限'.var_dump([
                                            'app' => $app,
                                            'name' => $name,
                                            'power' => $power,
                                            'data' => $data,
                                        ]));
                                    }
                                    return false;
                                } 

                            }
                        }
                    }
                }
            }
        }

        return true;
    }

    private function clearPowerExtendCache(){
        adminUser::del('admin-search-grouplist');
        adminUser::del('admin-manage-grouplist');
    }


    public function onTest(){
        print_r($_SESSION);
        
        if (!$this->inGroupPower(2)){
            throw new \Exception('没有权限');
        }else{
            return ;
        }

        
       // return $this->displayBlank('index_test');
    }


    
}